//
//  FirstPageViewController.m
//  BSLCar
//
//  Created by dlios on 15/5/22.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "FirstPageViewController.h"
#import "FirstPageTableViewCell.h"
#import "FirstPageURLRequest.h"
#import <UIImageView+WebCache.h>
#import <SDImageCache.h>
#import <AFNetworking.h>
#import <FMDatabase.h>
#import "FPOnMarkViewController.h"
#import "MJRefresh.h"
#import "OnMarkDetailViewController.h"
#import "FPScrollViewController.h"

@interface FirstPageViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, UIGestureRecognizerDelegate>

{
    UILabel *popLabel;
}

@property (nonatomic, retain) NSArray *carGroups;
@property (nonatomic, retain) UITableView *mTableView;
@property (nonatomic, retain) NSArray *dataArray;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@property (nonatomic, retain) FMDatabase *db;
@property (nonatomic, retain) UIView *popupView;
@property (nonatomic, retain) NSArray *popupDataArray;
@property (nonatomic, retain) UIActivityIndicatorView *popupActivity;
@property (nonatomic, retain) UITableView *popupTableView;
@property (nonatomic, retain) NSString *cityId;
@property (nonatomic, retain) NSString *brandid;
@property (nonatomic, retain) UISegmentedControl *segment;

@end

@implementation FirstPageViewController

- (void)dealloc
{
    [_airMenuController release];
    [_menuTableview release];
    
    [_carGroups release];
    [_mTableView release];
    [_dataArray release];
    [_activityIndicator release];
    [_db release];
    [_popupView release];
    [_popupDataArray release];
    [_popupActivity release];
    [_popupTableView release];
    [_cityId release];
    [_brandid release];
    [_segment release];
    
    [super dealloc];
}

- (UIView *)initPopupView {
    if (_popupView == nil) {
        _popupView = [[UIView alloc] init];
        UISwipeGestureRecognizer *swipt = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(click:)];
        swipt.direction = UISwipeGestureRecognizerDirectionRight;
        [_popupView addGestureRecognizer:swipt];
        swipt.delegate = self;
    }
    return _popupView;
}
- (void)click:(UISwipeGestureRecognizer *)swip {
    [UIView animateWithDuration:1 animations:^{
        self.popupView.frame = CGRectMake(self.view.bounds.size.width, 0, 0, 0);
    }];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (UISegmentedControl *)initSegment {

    _segment = [[UISegmentedControl alloc] initWithItems:@[@"在售",@"停售"]];
    _segment.selectedSegmentIndex = 0;
    _segment.tintColor = [UIColor clearColor];
    return _segment;
}

- (UITableView *)initPopupTableView {
    if (_popupTableView == nil) {
        _popupTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, self.view.bounds.size.width, self.view.bounds.size.height - 115) style:UITableViewStylePlain];
    }
    return _popupTableView;
}

- (BOOL)insertData:(NSString *)image {
    NSString *sqlInsertData = [NSString stringWithFormat:@"insert into FP(data) values('%@')", image];
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:sqlInsertData];
        [self.db close];
        if (result) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)createTable {
    NSString *sqlCreateTable = [NSString stringWithFormat:@"create table if not exists FP(id integer primary key autoincrement, data text)"];
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:sqlCreateTable];
        [self.db close];
        if (result) {
            return YES;
        }
    }
    return NO;
}

- (void)selectData {
    NSString *sqlSelect = [NSString stringWithFormat:@"select * from FP"];
    NSMutableArray *rootArray = [NSMutableArray array];
    if ([self.db open]) {
        FMResultSet *set = [self.db executeQuery:sqlSelect];
        NSData *data = [NSData data];
        while ([set next]) {
            NSString *string = [set objectForColumnName:@"data"];
            if (string.length != 0) {
                data = [string dataUsingEncoding:NSUTF8StringEncoding];
            }
        }
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic2 = [dic objectForKey:@"result"];
        NSArray *array = [dic2 objectForKey:@"brandlist"];
        NSMutableArray *secondArray = [NSMutableArray array];
        for (NSDictionary *dic3 in array) {
            NSArray *arr = [dic3 objectForKey:@"list"];
            NSString *letter = [dic3 objectForKey:@"letter"];
            [secondArray addObject:letter];
            NSMutableArray *secArray = [NSMutableArray array];
            for (NSDictionary *dic4 in arr) {
                FirstPageModel *model = [FirstPageModel getFirstPageModel];
                model.brandid = [[dic4 objectForKey:@"brandid"] stringValue];
                model.imgurl = [dic4 objectForKey:@"imgurl"];
                model.name = [dic4 objectForKey:@"name"];
                [secArray addObject:model];
            }
            [rootArray addObject:secArray];
        }
        [rootArray insertObject:secondArray atIndex:0];
        [self.activityIndicator stopAnimating];
        self.dataArray = rootArray;
        [self.view addSubview:[self createmTableView]];
    }
    [self.db close];
}


#pragma mark -- 判断网络连接
- (void)reachability {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // -1 NSLog(@"未知");
            {
                [self.activityIndicator stopAnimating];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络出错" message:@"请重新启动" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [self.view addSubview:alert];
                [alert show];
                break;
            }
            case AFNetworkReachabilityStatusNotReachable: // 0 NSLog(@"无连接");
            {
                [self selectData];
                UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"无网络连接" message:@"请连接网络" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
                [self.view addSubview:alert2];
                [alert2 show];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: // 2 NSLog(@"wifi");
                self.dataArray = [self getParserResult];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:  // 1 NSLog(@"3G");
            {
                UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"当前网络为2G/3G/4G" message:@"将会使用您的数据流量" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
                [self.view addSubview:alert3];
                alert3.tag = 103;
                [alert3 show];
                break;
            }
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 103) {
        if (buttonIndex == 1) {
            self.dataArray = [self getParserResult];
        }
        if (buttonIndex == 0) {
            [self selectData];
        }
    }
}

#pragma mark --网络请求 + 数据解析
- (NSArray *)getParserResult {
    
    NSMutableArray *rootArray = [NSMutableArray array];
    NSString *string = @"http://baojia.qichecdn.com/priceapi3.9.2/services/cars/brands?ts=0&app=a2&platform=pm1&version=3.9.2";
    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //请求
        NSString *sqlSelect = [NSString stringWithFormat:@"select * from FP"];
        NSMutableArray *arr = [NSMutableArray array];
        if ([self.db open]) {
            FMResultSet *set = [self.db executeQuery:sqlSelect];
            while ([set next]) {
                NSString *str = [set objectForColumnName:@"data"];
                if (str.length != 0) {
                    [arr addObject:str];
                }
            }
        }
        
        if (arr.count == 0) {
            NSString *sring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [self insertData:sring];
        }
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic2 = [dic objectForKey:@"result"];
        NSArray *array = [dic2 objectForKey:@"brandlist"];
        NSMutableArray *secondArray = [NSMutableArray array];
        for (NSDictionary *dic3 in array) {
            NSArray *arr = [dic3 objectForKey:@"list"];
            NSString *letter = [dic3 objectForKey:@"letter"];
            [secondArray addObject:letter];
            NSMutableArray *secArray = [NSMutableArray array];
            for (NSDictionary *dic4 in arr) {
                FirstPageModel *model = [FirstPageModel getFirstPageModel];
                model.brandid = [[dic4 objectForKey:@"brandid"] stringValue];
                model.imgurl = [dic4 objectForKey:@"imgurl"];
                model.name = [dic4 objectForKey:@"name"];
                [secArray addObject:model];
            }
            [rootArray addObject:secArray];
        }
        [rootArray insertObject:secondArray atIndex:0];
        [self.activityIndicator stopAnimating];
        [self.view addSubview:[self createmTableView]];
    }];
    return rootArray;
}

- (void)barButtonAction:(UIBarButtonItem *)barButton {
    if ([[XDKAirMenuController sharedMenu] isMenuOpened]) {
        
        [[XDKAirMenuController sharedMenu] closeMenuAnimated];
    } else {
        [[XDKAirMenuController sharedMenu] openMenuAnimated];
    }
}

#pragma mark
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    item.title = @"返回";
    self.navigationItem.backBarButtonItem = item;
    [item release];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(-5, 0, 25, 23);
    [button setImage:[UIImage imageNamed:@"iconfont-caidan.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(barButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] autorelease] initWithCustomView:button];
    
    [self initPopupView];
    [self initSegment];
    [self initPopupTableView];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    popLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    
    [self createRootView];
}

- (void)createRootView {
    
    [self reachability];
    
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *string = [array lastObject];
    NSString *path = [string stringByAppendingPathComponent:@"FP.sqlite"];
    
    self.db = [FMDatabase databaseWithPath:path];
    [self createTable];
    
    self.navigationItem.title = @"首页";
    
    self.dataArray = [NSArray array];
    
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.activityIndicator.center = self.view.center;
    [self.activityIndicator startAnimating];
    self.activityIndicator.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.activityIndicator];
    
    [_activityIndicator release];
}
#pragma mark --创建tableView 视图
- (UITableView *)createmTableView {
    
    self.mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.mTableView.tag = 1000;
    self.mTableView.dataSource = self;
    self.mTableView.delegate = self;
    self.mTableView.tableHeaderView = [self createTableHeaderView];

    return self.mTableView;
}

#pragma mark --tableview 头视图
- (UIView *)createTableHeaderView {
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 220)];
    myView.backgroundColor = [UIColor whiteColor];
    [myView addSubview:[self createScrollView]];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 160 + 5, self.view.bounds.size.width - 25, 1)];
    label.backgroundColor = [UIColor grayColor];
    [myView addSubview:label];
    [label release];
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(5, myView.bounds.size.height - 5, self.view.bounds.size.width - 25, 1)];
    label2.backgroundColor = [UIColor grayColor];
    [myView addSubview:label2];
    [label2 release];
    
    UILabel *labelBut1 = [[UILabel alloc] initWithFrame:CGRectMake(5, label.frame.origin.y + label.bounds.size.height, 1, label2.frame.origin.y - label.frame.origin.y)];
    labelBut1.backgroundColor = [UIColor grayColor];
    [myView addSubview:labelBut1];
    
    UILabel *labelBut5 = [[UILabel alloc] initWithFrame:CGRectMake(myView.bounds.size.width - 20, label.frame.origin.y + label.bounds.size.height, 1, label2.frame.origin.y - label.frame.origin.y)];
    labelBut5.backgroundColor = [UIColor grayColor];
    [myView addSubview:labelBut5];
    
    UILabel *labelBut3 = [[UILabel alloc] initWithFrame:CGRectMake((myView.bounds.size.width - 25) / 3, label.frame.origin.y + label.bounds.size.height, 1, label2.frame.origin.y - label.frame.origin.y)];
    labelBut3.backgroundColor = [UIColor grayColor];
    [myView addSubview:labelBut3];
    
    UILabel *labelBut4 = [[UILabel alloc] initWithFrame:CGRectMake((myView.bounds.size.width - 25) / 3 * 2, label.frame.origin.y + label.bounds.size.height, 1, label2.frame.origin.y - label.frame.origin.y)];
    labelBut4.backgroundColor = [UIColor grayColor];
    [myView addSubview:labelBut4];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake((labelBut1.frame.origin.x + labelBut3.frame.origin.x) / 2 - 40, 140, 80, 80);
    [button1 setImage:[UIImage imageNamed:@"iconfont-shangshi"] forState:UIControlStateNormal];
    button1.titleLabel.numberOfLines = 0;
    [button1.titleLabel sizeToFit];
    [button1 addTarget:self action:@selector(bntclick:) forControlEvents:UIControlEventTouchUpInside];
    button1.tag = 100;
    [button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [myView addSubview:button1];
    
    UILabel *lalbel7 = [[UILabel alloc]initWithFrame:CGRectMake((labelBut1.frame.origin.x + labelBut3.frame.origin.x) / 2 - 30, 165, 150, 80)];
    lalbel7.textColor = [UIColor orangeColor];
    lalbel7.text = @"新车上市";
    lalbel7.font = [UIFont systemFontOfSize:15];
    [myView addSubview:lalbel7];
    
    
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    button3.frame = CGRectMake((labelBut3.frame.origin.x + labelBut4.frame.origin.x) / 2 - 40, 140, 80, 80);
  
    [button3 setImage:[UIImage imageNamed:@"iconfont-tubiaozitihua24"] forState:UIControlStateNormal];
    button3.titleLabel.numberOfLines = 0;
    [button3.titleLabel sizeToFit];
    [button3 addTarget:self action:@selector(bntclick:) forControlEvents:UIControlEventTouchUpInside];
    button3.tag = 300;
    [button3 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [myView addSubview:button3];
    
    UILabel *label6 = [[UILabel alloc]initWithFrame:CGRectMake((labelBut3.frame.origin.x + labelBut4.frame.origin.x) / 2 - 30, 165, 150, 80)];
    label6.text = @"即将销售";
    label6.font = [UIFont systemFontOfSize:15];
    label6.textColor = [UIColor orangeColor];
    [myView addSubview:label6];
    
    UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
    button4.frame = CGRectMake((labelBut4.frame.origin.x + labelBut5.frame.origin.x) / 2 - 40, 140, 80, 80);
    [button4 setImage:[UIImage imageNamed:@"iconfont-paixing"] forState:UIControlStateNormal];
    button4.titleLabel.numberOfLines = 0;
    [button4.titleLabel sizeToFit];
    [button4 addTarget:self action:@selector(bntclick:) forControlEvents:UIControlEventTouchUpInside];
    button4.tag = 400;
    [button4 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [myView addSubview:button4];
    
    UILabel *label8 = [[UILabel alloc]initWithFrame:CGRectMake((labelBut4.frame.origin.x + labelBut5.frame.origin.x) / 2 - 30, 165, 150, 80)];
    label8.text = @"销售排行";
    label8.font = [UIFont systemFontOfSize:15];
    label8.textColor = [UIColor orangeColor];
    [myView addSubview:label8];

    return myView;
}

#pragma mark --but点击事件
- (void)bntclick:(UIButton *)sender {
    if (sender.tag == 100) {
        FPOnMarkViewController *fpom = [[FPOnMarkViewController alloc] init];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:fpom animated:NO];
        self.hidesBottomBarWhenPushed = NO;
        [fpom release];
    }
    if (sender.tag == 300) {
        FPWillSaleViewController *fpws = [[FPWillSaleViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:fpws animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        [fpws release];
    }
    if (sender.tag == 400) {
        FPRankingViewController *fprs = [[FPRankingViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:fprs animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        [fprs release];
    }
}

#pragma mark --scrollView
- (CycleScrollView *)createScrollView {
    
    CycleScrollView *scorllView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 160) animationDuration:4];
    
    NSMutableArray *viewsArray = [NSMutableArray array];
    
    NSArray *picUrlArray = [FirstPageURLRequest getParserResult];
    
    for (int i = 0; i < picUrlArray.count - 1; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, scorllView.bounds.size.height)];
        NSURL *url = [NSURL URLWithString:[picUrlArray objectAtIndex:i]];
        [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Bei"]];
//        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [viewsArray addObject:imageView];
    }
    scorllView.backgroundColor = [[UIColor purpleColor] colorWithAlphaComponent:0.1];
    scorllView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        return viewsArray[pageIndex];
    };
    scorllView.totalPagesCount = ^NSInteger(void){
        return picUrlArray.count - 1;
    };
    scorllView.TapActionBlock = ^(NSInteger pageIndex){
        //        NSLog(@"点击了第%d个",pageIndex);
        NSArray *array = [picUrlArray lastObject];
        NSArray *secA = [array lastObject];
        FPScrollViewController *fpsc = [[FPScrollViewController alloc] init];
        fpsc.url = [array objectAtIndex:pageIndex];
        fpsc.name = [secA objectAtIndex:pageIndex];
        [self.navigationController pushViewController:fpsc animated:YES];
        [fpsc release];
    };
    return scorllView;
}
#pragma mark --弹出视图
- (void)parserAndUrlRequ:(NSString *)strUrl {
    NSMutableArray *rootArr = [NSMutableArray array];
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:20];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dict = [diction objectForKey:@"result"];
            NSArray *firArr = [dict objectForKey:@"fctlist"];
            for (NSDictionary *dic in firArr) {
                NSMutableArray *secArr = [NSMutableArray array];
                [secArr addObject:[dic objectForKey:@"name"]];
                NSArray *array = [dic objectForKey:@"serieslist"];
                for (NSDictionary *d in array) {
                    FPRankingModel *model = [FPRankingModel getFPRankingModel];
                    model.id1 = [[d objectForKey:@"id"] integerValue];
                    model.imgurl = [d objectForKey:@"imgurl"];
                    model.name = [d objectForKey:@"name"];
                    model.price = [d objectForKey:@"price"];
                    [secArr addObject:model];
                }
                [rootArr addObject:secArr];
            }
        }
        self.popupDataArray = rootArr;
        [self createPopupTableView];
        [self.popupTableView reloadData];
        if (self.popupDataArray.count == 0) {
            [self notDataView];
        }
    }];
}

- (void)notDataView {

    popLabel.text = @"目前没有您要的数据";
    popLabel.textColor = [UIColor grayColor];
    popLabel.numberOfLines = 0;
    [popLabel sizeToFit];
    popLabel.frame = CGRectMake(100, self.view.bounds.size.height / 2 - 80, 100, 100);
    [self.popupView addSubview:popLabel];
}

- (void)createPopupView {
    self.popupView.backgroundColor = [UIColor whiteColor];
    self.popupView.frame = CGRectMake(self.view.bounds.size.width, 0, 0, 0);
    [self.view addSubview:self.popupView];

    self.segment.tintColor = [UIColor colorWithRed:96 / 255.0 green:96 / 255.0 blue:96 / 255.0 alpha:1];
    self.segment.frame = CGRectMake(02, 5, self.view.bounds.size.width - 104, 45);
    [self.segment addTarget:self action:@selector(changeSg:) forControlEvents:UIControlEventValueChanged];
    [self.popupView addSubview:self.segment];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    self.cityId = [user objectForKey:@"cityid"];
    
    self.popupView.userInteractionEnabled = YES;
    
    NSString *srt = @"http://baojia.qichecdn.com/priceapi3.9.2/services/seriesprice/get?brandid=";
    srt = [NSString stringWithFormat:@"%@%@&salestate=1&cityid=%@", srt, self.brandid, self.cityId];
    
    [self parserAndUrlRequ:srt];
}

- (void)changeSg:(UISegmentedControl *)seg {
    NSString *st = @"http://baojia.qichecdn.com/priceapi3.9.2/services/seriesprice/get?brandid=";
    NSString *urlStr = nil;
    if (seg.selectedSegmentIndex == 0) {
        urlStr = [NSString stringWithFormat:@"%@%@&salestate=%d&cityid=%@", st, self.brandid, 1, self.cityId];
    }
    if (seg.selectedSegmentIndex == 1) {
        urlStr = [NSString stringWithFormat:@"%@%@&salestate=%d&cityid=%@", st, self.brandid, 3, self.cityId];
    }
    [self parserAndUrlRequ:urlStr];
}
- (void)createPopupTableView {
    self.popupTableView.delegate = self;
    self.popupTableView.dataSource = self;
    self.popupTableView.tag = 2000;
    [self.popupView addSubview:self.popupTableView];
    
    self.popupTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
#pragma mark - tableView 数据源方法
/**分组总数*/
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 1000) {
        return self.dataArray.count - 1;
    }
    if (tableView.tag == 2000) {
        return self.popupDataArray.count;
    }
    return 0;
}

/**每一组多少行 ，section是第几组*/
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 1000) {
        NSArray *modelArray = [self.dataArray objectAtIndex:section + 1];
        return modelArray.count;
    }
    if (tableView.tag == 2000) {
        NSArray *array = [self.popupDataArray objectAtIndex:section];
        return array.count - 1;
    }

    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 1000) {
        return 60;
    }
    if (tableView.tag == 2000) {
        return 90;
    }
    return 0;
}

/**单元格*/
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 1000) {
        static NSString *identifer = @"cell";
        FirstPageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[FirstPageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
        NSArray *modelArray = [self.dataArray objectAtIndex:indexPath.section + 1];
        FirstPageModel *model = [modelArray objectAtIndex:indexPath.row];
//        cell.model = model;
        cell.picture.image = model.image;
        cell.nameLabel.text = model.name;
        NSURL *url = [NSURL URLWithString:model.imgurl];
        [cell.picture sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"bei2"]];
        cell.picture.contentMode = UIViewContentModeScaleAspectFit;
        return cell;
    }
    if (tableView.tag == 2000) {
        static NSString *identifierPopup = @"popupCell";
        FirstPageRankingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierPopup];
        if (!cell) {
            cell = [[FirstPageRankingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierPopup];
        }
        
        NSArray *array = [self.popupDataArray objectAtIndex:indexPath.section];
        FPRankingModel *model = [array objectAtIndex:indexPath.row + 1];
        NSURL *url = [NSURL URLWithString:model.imgurl];
        [cell.mimageview sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Bei"]];
        cell.mimageview.contentMode = UIViewContentModeScaleAspectFit;
        cell.labelName1.text = model.name;
        cell.labelName1.font = [UIFont systemFontOfSize:14];
        if ([model.price isEqualToString:@"暂无"] || [model.price isEqualToString:@"停售"]) {
            cell.priceLabel.text = [NSString stringWithFormat:@"%@", model.price];
        } else {
            cell.priceLabel.text = [NSString stringWithFormat:@"%@万", model.price];
            cell.priceLabel.font = [UIFont systemFontOfSize:14];
        }
        return cell;
    }
    return nil;
}

/**每一组的标题*/
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 1000) {
        NSArray *modelArray = [self.dataArray objectAtIndex:0];
        return [modelArray objectAtIndex:section];
    }
    if (tableView.tag == 2000) {
        NSArray *ar = [self.popupDataArray objectAtIndex:section];
        return [ar objectAtIndex:0];
    }
    return nil;
}

/** 右侧索引列表*/
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView.tag == 1000) {
        NSArray *outArray = [self.dataArray objectAtIndex:0];
        return outArray;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 1000) {
        NSArray *modelArray = [self.dataArray objectAtIndex:indexPath.section + 1];
        FirstPageModel *model = [modelArray objectAtIndex:indexPath.row];

        self.brandid = model.brandid;
        [self createPopupView];
        [self.popupTableView reloadData];
        [UIView animateWithDuration:.3 animations:^{
            self.popupView.frame = CGRectMake(100, 0, self.view.bounds.size.width - 100, self.view.bounds.size.height);
        }];
    }
    if (tableView.tag == 2000) {
        OnMarkDetailViewController *onMark = [[OnMarkDetailViewController alloc] init];
        NSArray *array = [self.popupDataArray objectAtIndex:indexPath.section];
        FPRankingModel *model = [array objectAtIndex:indexPath.row + 1];
        onMark.idDetail = [NSString stringWithFormat:@"%ld", model.id1];
        onMark.carName = model.name;
        [self.navigationController pushViewController:onMark animated:YES];
        [onMark release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
